package com.life.notes.config.interceptor;

import com.life.notes.config.constant.Constant;
import com.life.notes.config.security.model.SysUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * 用户参数拦截器
 * @author lishuqian
 * @date 2020/6/15
 */
@Slf4j
public class UserAuthRestInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                if ("Accept-Encoding".toUpperCase().equals(name.toUpperCase())){
                    continue;
                }
                String values = request.getHeader(name);
                BaseContextHandler.set(name.toUpperCase(), values);
            }
        }
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof SysUserDetails){
            SysUserDetails userDetails = (SysUserDetails) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();
            Integer userId = userDetails.getId();
            BaseContextHandler.set(Constant.HEADER_CURRENT_USER,userId);
            log.info("Interceptor userId:"+userId+";昵称:"+userDetails.getUsername());
        }
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //上下文属性值清除，防止内存泄漏
        BaseContextHandler.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}